﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BakalarskaPraca.Forms.Controls;
using BakalarskaPraca.Generation.Data;

namespace BakalarskaPraca.Forms
{
    public partial class ProgressViewer : Form
    {
        private readonly Action _afterGenerationCallback;

        public ProgressViewer(List<MarkedPolygonGroup> generationGroups, Action afterGenerationCallback)
        {
            _afterGenerationCallback = afterGenerationCallback;
            InitializeComponent();
            generationGroups.ForEach(
                g => this.MainPanel.Controls.Add(new GenerationRunner(g, this.CheckForCompletion)));
        }

        public void CheckForCompletion()
        {
            if (this.MainPanel.Controls.Cast<GenerationRunner>().All(r => r.Completed))
            {
                this._afterGenerationCallback();
                if (Properties.Settings.Default.CloseAfterGeneration)
                {
                    Application.Exit();
                } 
                else
                {
                    MessageBox.Show("Done...");
                    this.Close();
                }
            }
        }

        private void MainPanelControlAdded(object sender, ControlEventArgs e)
        {
            e.Control.Width = this.MainPanel.Width - 5;
            var generationRunner = e.Control as GenerationRunner;
            if (generationRunner != null) generationRunner.RunGeneration();
        }

        private void ProgressViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.MainPanel.Controls.Cast<GenerationRunner>().All(r => r.Completed))
            {
                MessageBox.Show("You cannot close this form during generation process");
                e.Cancel = true;
            }
        }
    }
}
